
let offsetTop = 0;
const tg = window.Telegram.WebApp;
const cartKey = `cart_${location.pathname.split('/')[2]}`;

function filterCurrencySymbol(cost) {
    const symbol = window.currencySymbol;
    const position = window.currencyPosition;
    switch (position) {
        case 'left':
            cost = symbol + ' ' + cost;
            break;
        case 'right':
            cost = cost + ' ' + symbol;
            break;
        case 'left_without_space':
            cost = symbol + cost;
            break;
        case 'right_without_space':
            cost = cost + symbol;
            break;
    }

    return cost;
}

if (tg) {
    tg.expand();
    // tg.enableClosingConfirmation();
    tg.MainButton.textColor = '#fff';
    tg.MainButton.color = '#5E30EB';
}

if (localStorage.getItem(cartKey)) {
    const localCart = JSON.parse(localStorage.getItem(cartKey));
    if (Array.isArray(localCart)) localStorage.setItem(cartKey, JSON.stringify({ items: [], delivery: {}, payment: {} }));
}

document.addEventListener('click', e => {
	if (e.target.classList.contains('js-open-modal-promocode')) {
		document.querySelector('.modal-container').classList.add('active');
	}

	if (e.target.classList.contains('modal-container')) {
		e.target.classList.remove('active');
	}
});

document.addEventListener('input', e => {
	if (e.target.classList.contains('js-input-uppercase')) {
		const input = e.target;
		input.value = input.value.toUpperCase();
	}
});

document.addEventListener('submit', async e => {
	if (e.target.classList.contains('modal-form')) {
		e.preventDefault();
		const $modalForm = e.target;
		const $modalFormInput = $modalForm.querySelector('input[name=code]');
		const $modalFormInputType = $modalForm.querySelector('input[name=type]');
		const $modalFormBtn = $modalForm.querySelector('.modal-form-btn');
		const $btnOpenModalPromocode = document.querySelector('.cart-promocode-btn');
		const type = $modalFormInputType.value;
		const cart = getCart();

		if ($modalForm.querySelector('.error-text') != null) $modalForm.querySelector('.error-text').remove();

		if (type == 'add') {
			const code = $modalFormInput.value;
			const response = await checkPromocode(code);
			if (response.success) {
				if ($btnOpenModalPromocode != null) {
					$btnOpenModalPromocode.innerText = response.message;
					$btnOpenModalPromocode.classList.add('cart-promocode-btn-green');
				}
				$modalFormInput.value = response.promocode_name;
				$modalFormBtn.innerText = 'Delete promocode';
				$modalFormInputType.value = 'remove';
				$modalForm.closest('.modal-container').classList.remove('active');
				setCartPromocode(response.promocode_id, response.promocode_name, response.discount_value);
			} else {
				if (!cart.hasOwnProperty('promocode')) {
                    $modalFormBtn.innerText = 'Submit';
					$modalFormInputType.value = 'add';
					$modalFormInput.insertAdjacentHTML('afterend', `<p class="error-text">${response.message}</p>`);
				} else removeCartPromocode();
			}
		} else if (type == 'remove') {
			const $btnOpenModalPromocode = document.querySelector('.cart-promocode-btn');
			if ($btnOpenModalPromocode != null) {
				$btnOpenModalPromocode.classList.remove('cart-promocode-btn-green');
				$btnOpenModalPromocode.innerText = 'Enter promocode';
			}
			$modalFormInput.value = '';
			$modalFormInputType.value = 'add';
            $modalFormBtn.innerText = 'Submit';
			removeCartPromocode();
		}
	}
});

document.addEventListener('click', e => {
    if (e.target.classList.contains('js-open-modal-promocode')) {
        document.querySelector('.modal-container').classList.add('active');
    }

    if (e.target.classList.contains('modal-container')) {
        e.target.classList.remove('active');
    }
});

document.addEventListener('input', e => {
    if (e.target.classList.contains('js-input-uppercase')) {
        const input = e.target;
        input.value = input.value.toUpperCase();
    }
});

const cart = getCart();

function getCart() {
    return JSON.parse(localStorage.getItem(cartKey)) || { items: [], delivery: {}, payment: {} };
}

function addCartItem(product) {
    const cart = getCart();
    cart.items.push(product);
    localStorage.setItem(cartKey, JSON.stringify(cart));
    renderCartTotal();
}

function removeCartItem(productId) {
    const cart = getCart();
    const index = cart.items.findIndex(item => item.id == productId);
    cart.items.splice(index, 1);
    localStorage.setItem(cartKey, JSON.stringify(cart));
    renderCartTotal();
}

function removeCartItemForIndex(index) {
    const cart = getCart();
    cart.items.splice(index, 1);
    localStorage.setItem(cartKey, JSON.stringify(cart));
    renderCartTotal();
}

function incrementCartItem(productId) {
    const cart = getCart();
    const index = cart.items.findIndex(item => item.id == productId);
    cart.items[index].count += 1;
    localStorage.setItem(cartKey, JSON.stringify(cart));
    renderCartTotal();
}

function decrementCartItem(productId) {
    const cart = getCart();
    const index = cart.items.findIndex(item => item.id == productId);
    if (cart.items[index].count == 1) {
        removeCartItem(productId);
        return false;
    }
    if (cart.items[index].count > 1) {
        cart.items[index].count -= 1;
    }
    localStorage.setItem(cartKey, JSON.stringify(cart));
    renderCartTotal();
}

function incrementCartItemForIndex(index) {
    const cart = getCart();
    cart.items[index].count += 1;
    localStorage.setItem(cartKey, JSON.stringify(cart));
    renderCartTotal();
}

function decrementCartItemForIndex(index) {
    const cart = getCart();
    if (cart.items[index].count > 1) {
        cart.items[index].count -= 1;
    }
    localStorage.setItem(cartKey, JSON.stringify(cart));
    renderCartTotal();
}

function setCountCartItem(productId, count) {
    const cart = getCart();
    const index = cart.items.findIndex(item => item.id == productId);
    cart.items[index].count = count;
    localStorage.setItem(cartKey, JSON.stringify(cart));
    renderCartTotal();
}

function setCountCartItemForIndex(index, count) {
    const cart = getCart();
    cart.items[index].count = count;
    localStorage.setItem(cartKey, JSON.stringify(cart));
    renderCartTotal();
}

function checkCartItem(productId) {
    const cart = getCart();
    const index = cart.items.findIndex(item => item.id == productId);
    return cart.items[index];

}


function getCartItems(productId) {
    const cart = getCart();
    return cart.items.filter((item, index) => {
        item.index = index;
        return item.id == productId;
    });
}

function clearCart() {
    const cart = getCart();
    cart.items = [];
    localStorage.setItem(cartKey, JSON.stringify(cart));
    renderCartTotal();
}

function setCartPayment(methodId, methodProviderId = false) {
    const cart = getCart();
    cart.payment.id = methodId;
    if (methodProviderId) cart.payment.providerId = methodProviderId;
    if (cart.payment.providerId && !methodProviderId) delete cart.payment.providerId;
    localStorage.setItem(cartKey, JSON.stringify(cart));
    renderCartTotal();
}

function setCartPromocode(id, code, discountValue) {
	const cart = getCart();
	cart.promocode = {
        id,
		code,
		discountValue
	}
	localStorage.setItem(cartKey, JSON.stringify(cart));
	renderCartTotal();
}

function removeCartPromocode() {
	const cart = getCart();
	if (cart.hasOwnProperty('promocode')) delete cart.promocode;
	localStorage.setItem(cartKey, JSON.stringify(cart));
	renderCartTotal();
}

async function calculateDiscount(product_id, product_count) {
    // Рассчет скидок

    const http = new HTTP();
    const params = new URLSearchParams({
         user_tg_id: tg.initDataUnsafe.user.id,
        product_id: product_id,
        product_count: product_count,
    });
    const formData = new FormData();
    formData.append('cart_data', JSON.stringify(getCart()));
    const url = "products/calculate_discount/?" + params.toString()

    try {
        const response = await http.sendRequest('POST', url, formData);
        return await response.json()
    } catch (e) {
        console.log(e);
    }
}


async function renderCartTotal() {
    const cart = getCart();
    let totalPrice = 0;
    if (cart.items.length > 0) {
        for (const product of cart.items) {
            let productPrice = await calculateDiscount(product.id, product.count)

            totalPrice += productPrice * product.count;
        }
        if (cart.hasOwnProperty('promocode')) {
            const promocode = cart.promocode;
            totalPrice -= totalPrice * (promocode.discountValue / 100);
         }
        $('.go-to-order-wrap').removeClass('hidden');
        $('.go-to-order-wrap').text(filterCurrencySymbol(totalPrice));
    } else {
        $('.go-to-order-wrap').addClass('hidden');
        $('.go-to-order-wrap').text('');
        $('.js-cart-products').html('<p class="cart-bg-text">Cart is empty</p>');
    }
}

function setCartField(key, value) {
    const cart = getCart();
    cart[key] = value;
    localStorage.setItem(cartKey, JSON.stringify(cart));
}

function redirect(name) {
    const html = $(`#${name}`).html();
    $('.page-wrapper').html(html);
    pages[name]();
}

function redirectIndex() {
    redirect('index');
}

function redirectCart() {
    redirect('cart');
}

function redirectOrder() {
    redirect('order');
}

async function checkPromocode(code) {
	const cart = getCart();
	const url = window.checkPromocodeUrl;
	const http = new HTTP();
	const formData = new FormData();
	formData.append('cart', JSON.stringify(cart));
	formData.append('user_tg_id', tg.initDataUnsafe.user.id);
	formData.append('shop_id', tg.initDataUnsafe.shop_id);
	formData.append('promocode_name', code);
	let response = false;
	try {
		response = await http.sendRequest('POST', url, formData);
		response = await response.json();
        console.log(response)
	} catch (e) {
		console.log(e);
	}

	return response;
}

function update_cart() {
    // Обновляем корзину пользователя

    const $cartProducts = document.querySelector('.js-cart-products');
    const url = $cartProducts.dataset.createUrl;
    const formData = new FormData();
    formData.append('cart_data', JSON.stringify(getCart()));
    formData.append('user_tg_id', tg.initDataUnsafe.user.id)
    let promocode = getCart().promocode

    removeCartPromocode()
    sendCartData(url, formData);
}

function sendCartData(url, data) {
    if (tg) {
        tg.MainButton.showProgress(true);
    }
    try {
        const http = new HTTP();
        http.sendRequest('POST', url, data)
            .then(response => response.json())
            .then(response => {
                if (response.success) {
                    clearCart();
                    if (tg) {
                        tg.MainButton.showProgress(false);
                        tg.close();
                    }
                } else {
                    if (tg) tg.showAlert(response.error);
                }
            });
    } catch (e) {
        if (tg) tg.showAlert(e.toString());
    }
}


function checkCartLength() {
    const cart = getCart();
    return cart.items.length > 0;
}

function backButtonOffClick() {
    tg.BackButton.offClick(redirectIndex);
    tg.BackButton.offClick(redirectCart);
    tg.BackButton.offClick(hideCard);
}

function mainButtonOffClick() {
    tg.MainButton.offClick(redirectIndex);
    tg.MainButton.offClick(redirectCart);
    tg.MainButton.offClick(update_cart);
}

function refreshNavOverlay() {
    $('.nav').stop().animate({
        scrollLeft: $('.nav div.active')[0].offsetLeft - 15,
    }, 5);

    let currentWidth = $('.nav')
        .find('div.active')
        .width();

    let current = $('.nav')
        .find('div.active')
        .position();

    $('.nav-overlay').css({
        left: +current.left + $('.nav').scrollLeft(),
        width: currentWidth
    });
}

function setNav() {
    if ($('.nav').length) {
        let clickEventMenu = false;
        $('.nav').on('click', 'span', function(e) {
            e.preventDefault();

            clickEventMenu = true;

            $('.nav div').removeClass('active');
            $(this).parent().addClass('active');

            refreshNavOverlay();

            let targetId = $(this).data('target-cat');
            let wWidth = $(window).width();

            window.categoryId = targetId;

            $('html, body').animate({
                scrollTop: $(targetId).offset().top - (wWidth <= 450 ? 50 : 110),
            }, 300);
        });

        let menu_sticky = new StickySidebar('#nav-wrap', {
            topSpacing: 0,
            bottomSpacing: 0,
            containerSelector: '.catalog-item-wrap',
            innerWrapperSelector: '.nav',
        });

        let windowHeight = $(window).height();
        let stDirection = true; // true = вниз

        let indicator = new WheelIndicator({
            preventMouse: false,
            callback: function(e) {
                stDirection = e.direction === 'down';
            }
        });

        $(document).on('scroll', function(e) {
            if (!clickEventMenu) {
                $('div[data-target-block]').each(function(index) {
                    var self = $(this),
                        height;

                    height = self.offset().top + self.height() + 80;

                    const targetId = self.attr('id');

                    let currentItem = $('span[data-target-cat="#' + targetId + '"]').parent();

                    if ($(document).scrollTop() + windowHeight >= height) {
                        if (!self.hasClass('scrolled')) {
                            self.addClass('scrolled');

                            $('.nav div').removeClass('active');
                            currentItem.addClass('active');
                            window.categoryId = `#${targetId}`;

                            refreshNavOverlay();
                        }
                    }

                    height = self.offset().top + self.height() + 80;

                    if ($(document).scrollTop() <= height) {
                        self.removeClass('scrolled');
                        currentItem.addClass('active');
                        window.categoryId = `#${targetId}`;
                    }

                    if ($(document).scrollTop() == 0) {
                        $('.nav div').removeClass('active');
                        $('.nav div:nth-child(2)').addClass('active');
                        window.categoryId = '#cat-1';
                        refreshNavOverlay();
                    }
                });
            }

            setTimeout(function() {
                clickEventMenu = false;
            }, 300);
        });
    }
}


async function fetchProductsCategories(user_tg_id) {
    // Получаем товары и категории по API

    const http = new HTTP();
    const params = new URLSearchParams({
         user_tg_id: user_tg_id
    });
    const url = "products/?" + params.toString()


    try {
        const response = await http.sendRequest('GET', url);
        return await response.json()
    } catch (e) {
        console.log(e);
    }

}

async function getBotStatus() {
    // Получаем статус бота

    const http = new HTTP();
    const url = "bot_status/"

    try {
        const response = await http.sendRequest('GET', url);
        return await response.json()
    } catch (e) {
        console.log(e);
    }

}

function createNav(categories) {
    // Создаем навигацию

    const $nav = document.querySelector('.nav')
    if ($nav != null) {
        categories.forEach((item, _) => {
            $nav.insertAdjacentHTML('beforeend', `
            <div class="active">
            <span data-target-cat="#cat_${item.id}">${item.title}</span>
            </div>`)
        });
    }
}

function loadProducts(categories, products) {
    // Генерируем карточки с товарами

    const $catalog_container = document.querySelector('.catalog-container')

    if ($catalog_container != null) {
        categories.forEach((category_item, _) => {
            $catalog_container.insertAdjacentHTML('beforeend', `
            <div class="catalog-item-wrap" id="cat_${category_item.id}" data-target-block="">
            <div class="catalog-item-title">${category_item.title}</div>
            </div>`)
            const $categoryProducts = document.querySelector("#cat_" + category_item.id)
            products.forEach((item, _) => {
                if (item.category_id == category_item.id) {
                    $categoryProducts.insertAdjacentHTML('beforeend', `
                    <div class="catalog-item">
                    <div class="catalog-item-product js-get-product" data-link-get="/products/${item.id}" data-product-id="${item.id}" data-price="${item.price}" data-weight="" data-count="" data-available-quantity="${item.available_quantity}" data-variants="false" data-options="false">
                        <div class="ci-thumb">
                            <img src="./images/${item.image_path}" class="lazy" data-original="./images/${item.image_path}" alt="${item.title}" style="">
                        </div>
                        <div class="ci-name">${item.title}</div>
                        <div class="ci-weight" style="margin-bottom: 5px;">${item.weight} ${item.measurement == 'Штуки' ? 'pc' : 'gr'}</div>
                        <div class="ci-weight" style="margin-bottom: 5px; ${!item.strain_type ? 'display: none;' : ''}">Strain Type: ${item.strain_type ? item.strain_type.toUpperCase() : ''}</div>
                        <div class="ci-weight" style="${!item.thc ? 'display: none;' : ''}">THC: ${item.thc} %</div>
                    </div>
                    <div class="ci-price-counter">
                        <div class="ci-price touch-item" data-product-id="${item.id}">฿${item.price}</div>
                        <div class="ci-counter-wrap hidden">
                            <div class="cic-minus catalog touch-item">
                                <svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" x="0" y="0" viewBox="0 0 341.333 341.333" style="enable-background:new 0 0 512 512" xml:space="preserve" class="">
                                    <rect y="149.333" width="341.333" height="42.667" fill="#000000"></rect>
                                </svg>
                            </div>
                            <div class="cic-count">0</div>
                            <div class="cic-plus catalog touch-item disabled" data-product-id="${item.id}">
                                <svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" x="0" y="0" viewBox="0 0 341.4 341.4" style="enable-background:new 0 0 512 512" xml:space="preserve" class="">
                                    <polygon points="192,149.4 192,0 149.4,0 149.4,149.4 0,149.4 0,192 149.4,192 149.4,341.4 192,341.4 192,192 341.4,192 341.4,149.4" fill="#000000" class=""></polygon>
                                </svg>
                            </div>
                        </div>
                    </div>
                </div>
                    `);
                }
            });
        });
    }
}


function getParam(prop) {
    const getParamsStr = window.location.search;

    if (!getParamsStr) return false;

    const getParams = getParamsStr.replace('?', '').split('&').reduce((p, e) => {
        const a = e.split('=');
        p[decodeURIComponent(a[0])] = decodeURIComponent(a[1]);
        return p;
    }, {});

    if (!getParams[prop]) return false;

    return getParams[prop];
}

function showBotDisabledPopup(popup_content) {
    Swal.fire({
        icon: 'info',
        html: popup_content,
        showCloseButton: true,
        showConfirmButton: false,
    });
}

const pages = {
    index: async function() {
        if (tg) {
            backButtonOffClick();
            mainButtonOffClick();
            if (tg.BackButton.isVisible) tg.BackButton.hide();
            tg.MainButton.text = 'Order';
            tg.MainButton.onClick(redirectCart);
            if (!checkCartLength()) {
                if (tg.MainButton.isVisible) tg.MainButton.hide();
            } else {
                if (!tg.MainButton.isVisible) tg.MainButton.show();
            }
        }
        $('img.lazy').lazyload({
            threshold: 400
        });
        const [isBotEnabled, botDisabledUntil] = await getBotStatus();
        console.log(botDisabledUntil)

        if (!isBotEnabled) {
            if (!botDisabledUntil) {
                popup_text_en = "The bot only works for pre-orders. We will let you know as soon as the service becomes available"
                popup_text_ru = "Бот работает только на предзаказы. Сообщим вам, как только сервис станет доступным"
            } else {
                popup_text_en = "Delivery will be available tomorrow from 09:00 am (Bangkok time). You can create an order, but we will only deliver it tomorrow morning"
                popup_text_ru = "Доставка станет доступна завтра с 09:00 утра (по Бангкоку). Вы можете создать заказ, однако доставим его только завтра утром"
            }
            popup_content = `<div class="popup-message">${popup_text_en}</div><div class="popup-message">${popup_text_ru}</div>`
            showBotDisabledPopup(popup_content);
        }
        const [products, categories] = await fetchProductsCategories(tg.initDataUnsafe.user.id)
        createNav(categories);
        loadProducts(categories, products);
        setNav();
        refreshNavOverlay();

        if (window.categoryId) {
            $('html, body').animate({
                scrollTop: $(window.categoryId).offset().top - ($(window).width() <= 450 ? 50 : 110),
            }, 300);
        }

        if (document.querySelector('.catalog-container') != null) {
            const $items = document.querySelectorAll('.catalog-item-product');
            if ($items != null) {
                $items.forEach($item => {
                    const $itemCounter = $item.nextElementSibling;
                    $itemCounter.querySelector('.cic-plus').classList.remove('disabled');
                    $itemCounter.querySelector('.ci-price').classList.remove('hidden');
                    $itemCounter.querySelector('.ci-counter-wrap').classList.add('hidden');
                    $itemCounter.querySelector('.cic-count').innerText = 0;
                });
            }
            if (checkCartLength()) {
                const cart = getCart();
                cart.items.forEach(item => {
                    const $item = document.querySelector(`.catalog-item-product[data-product-id="${item.id}"]`);
                    if ($item != null && $item.nextElementSibling != null) {
                        const $itemCounter = $item.nextElementSibling;
                        if ($itemCounter != null) {
                            const productCount = parseInt($item.dataset.availableQuantity);
                            const oldCount = parseInt($itemCounter.querySelector('.cic-count').innerText);
                            if (!isNaN(productCount) && item.count >= productCount) {
                                $itemCounter.querySelector('.cic-plus').classList.add('disabled');
                            }
                            $itemCounter.querySelector('.ci-price').classList.add('hidden');
                            $itemCounter.querySelector('.ci-counter-wrap').classList.remove('hidden');
                            $itemCounter.querySelector('.cic-count').innerText = oldCount + item.count;
                            $item.dataset.currentCount = oldCount + item.count;
                        }
                    }
                });
            }
        }
        renderCartTotal();
    },
    cart: async function() {
        if (tg) {
            backButtonOffClick();
            mainButtonOffClick();
            if (!tg.BackButton.isVisible) tg.BackButton.show();
            tg.BackButton.onClick(redirectIndex);
            tg.MainButton.text = 'Confirm';
            tg.MainButton.disable();
            tg.MainButton.onClick(update_cart);
        }
        const cart = getCart();
        if (cart.hasOwnProperty('promocode')) {
            const response = await checkPromocode(cart.promocode.code);
            if (response.success) {
                const $modalForm = document.querySelector('.modal-form');
                const $modalFormInput = $modalForm.querySelector('input[name=code]');
                const $modalFormInputType = $modalForm.querySelector('input[name=type]');
                const $modalFormBtn = $modalForm.querySelector('.modal-form-btn');
                const $btnOpenModalPromocode = document.querySelector('.cart-promocode-btn');
                if ($btnOpenModalPromocode != null) {
                    $btnOpenModalPromocode.innerText = response.message;
                    $btnOpenModalPromocode.classList.add('cart-promocode-btn-green');
                }
                $modalFormInput.value = response.promocode_name;
                $modalFormBtn.innerText = 'Delete promocode';
                $modalFormInputType.value = 'remove';
            } else removeCartPromocode();
        }
        const $cartProducts = document.querySelector('.js-cart-products');
        if ($cartProducts != null) {
            const clearCartBtn = document.querySelector('.cart-empty');
            clearCartBtn.classList.remove('d-none');
            $cartProducts.innerHTML = '';
            const url = $cartProducts.dataset.checkUrl;
            const http = new HTTP();
            const formData = new FormData();
            formData.append('cart_data', JSON.stringify(getCart()));
            formData.append('user_tg_id', tg.initDataUnsafe.user.id)
            try {
                http.sendRequest('POST', url, formData)
                    .then(response => response.json())
                    .then(async response => {
                        if (response.success) {
                            if (tg) tg.MainButton.enable();
                        }
                        $cartProducts.innerHTML = '';
                        for (const item of response.items) {
                            const index = response.items.indexOf(item);
                            let options = ``;
                            let optionsPrice = 0;
                            if (item.variant) options += `${item.variant}<br>`;
                            if (Object.keys(item.options).length) {
                                for (key in item.options) {
                                    item.options[key].forEach(option => {
                                        options += `${option.name}<br>`;
                                        optionsPrice += parseInt(option.price);
                                    });
                                }
                            }

                            const productCount = parseInt(item.available_quantity);

                            let oldPrice = item.price * item.count;
                            let discountedItemPrice = await calculateDiscount(item.id, item.count)
                            const discountedPrice = discountedItemPrice * item.count

                            let old_item_price = filterCurrencySymbol(oldPrice);
                            let item_price = filterCurrencySymbol(discountedPrice);

                            // Формируем строку с зачеркнутой ценой
                            if (discountedPrice < oldPrice) {
                                item_price = `<del>${old_item_price}</del> <b>${filterCurrencySymbol(discountedPrice)}</b>`
                            }

                            $cartProducts.insertAdjacentHTML('beforeend', `
                            <div class="cart-item-row" data-product-id="${item.id}" data-index="${index}" data-product-count="${item.available_quantity}">
                                <div class="cart-item-thumb">
                                    <img src="${item.img}" alt="${item.title}">
                                </div>
                                <div class="cart-item-data">
                                    <div class="cart-item-label">${item.title}
                                        <div class="cart-item-caption">
                                            ${options}
                                        </div>    
                                        <span class="js-price" data-price="${discountedPrice}" data-item-price="${item.price}">${item_price}</span>
                                    </div>
                                    <div class="cart-item-counter ${!isNaN(productCount) && item.count > productCount ? 'cart-item-error' : ''}">
                                        <div class="cic-minus cart">
                                            <svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" x="0" y="0" viewBox="0 0 341.333 341.333" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""> <rect y="149.333" width="341.333" height="42.667" fill="#000000"></rect> </svg>
                                        </div>
                                        <div class="cic-count">${item.count}</div>
                                        <div class="cic-plus cart ${!isNaN(productCount) && item.count >= productCount ? 'disabled' : ''}">
                                            <svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" x="0" y="0" viewBox="0 0 341.4 341.4" style="enable-background:new 0 0 512 512" xml:space="preserve" class=""><polygon points="192,149.4 192,0 149.4,0 149.4,149.4 0,149.4 0,192 149.4,192 149.4,341.4 192,341.4 192,192 341.4,192 341.4,149.4 " fill="#000000" class=""></polygon></svg>
                                        </div>
                                        <span class="cart-item-tooltip">Selected amount is not available</span>
                                    </div>
                                </div>
                            </div>
                            `);
                        }
                    });
            } catch (e) {
                console.log(e);
            }
        }
        renderCartTotal();
    }
};

redirect('index');

async function getProduct(productId) {
    const $btn = document.querySelector(`.catalog-item-product[data-product-id="${productId}"]`);

    const getUrl = $btn.dataset.linkGet + "?user_tg_id=" + tg.initDataUnsafe.user.id;
    const http = new HTTP();
    try {
        const response = await http.sendRequest('GET', getUrl);
        const result = await response.json();
        const modal = document.querySelector('.product-view-wrap');
        const modalImage = modal.querySelector('.js-product-image');
        const modalTitle = modal.querySelector('.js-product-title');
        const modalWeight = modal.querySelector('.js-product-weight');
        const modalPrice = modal.querySelector('.js-product-price');
        const modalDescription = modal.querySelector('.js-product-description');
        const modalStrainType = modal.querySelector('.js-product-strain-type');
        const modalFeelings = modal.querySelector('.js-product-feelings');
        const modalGenetics = modal.querySelector('.js-product-genetics');
        const modalThc = modal.querySelector('.js-product-thc');
        const modalCbd = modal.querySelector('.js-product-cbd');

        const modalVariant = modal.querySelector('.js-product-variant');
        const modalOptions = modal.querySelector('.js-product-options');

        modalTitle.innerText = '';
        modalImage.src = '';
        modalWeight.innerText = '';
        modalDescription.innerText = '';
        modalStrainType.innerHTML = '';
        modalFeelings.innerHTML = '';
        modalGenetics.innerHTML = '';
        modalThc.innerHTML = '';
        modalCbd.innerHTML = '';

        modalVariant.innerHTML = '';
        modalOptions.innerHTML = '';
        modalPrice.innerText = '';

        if (result) {
            modalTitle.innerText = result.title;
            // modalWeight.innerText = result.data.weight;
            modalDescription.innerText = result.description;
            if (result.strain_type != null) {
                modalStrainType.innerHTML = `<b>Type:</b> ${result.strain_type.toUpperCase()}`
            }
            if (result.feelings != null && result.feelings.length > 0) {
                modalFeelings.innerHTML = `<b>Feelings:</b> ${result.feelings.map(elem => elem.title).join(', ')}`
            }
            if (result.genetics != null && result.genetics.length > 0) {
                modalGenetics.innerHTML = `<b>Genetics:</b> ${result.genetics.map(elem => elem.title).join(', ')}`
            }
            if (result.thc != null) {
                modalThc.innerHTML = `<b>THC:</b> ${result.thc} %`
            }
            if (result.cbd != null) {
                modalCbd.innerHTML = `<b>CBD:</b> ${result.cbd}`
            }
            modalPrice.innerText = result.price;
            modal.dataset.productId = result.id;
            modal.dataset.price = result.price;
            modal.dataset.count = result.count;
            if (result.image_path) {
                modalImage.src = "./images/" + result.image_path
                if (!modalImage.classList.contains('active')) modalImage.classList.add('active');
                if (!modalImage.classList.contains(result.image_form)) modalImage.classList.add(result.image_form);
            }
            modal.querySelector('.js-add-cart').innerText = 'Add';
            modal.querySelector('.js-add-cart').classList.remove('options-required');
            const productCount = parseInt(result.available_quantity);
            const count = parseInt(modal.querySelector('.pcw-count').innerText);
            const currentCount = parseInt($btn.dataset.currentCount);

            if (!isNaN(productCount) && count >= productCount) {
                modal.querySelector('.pcw-plus').classList.add('disabled');
            }
            if (!isNaN(currentCount) && !isNaN(productCount) && currentCount >= productCount) {
                modal.querySelector('.pcw-plus').classList.add('disabled');
                modal.querySelector('.pcw-minus').classList.add('disabled');
                modal.querySelector('.js-add-cart').classList.add('disabled');
            }
            if (!isNaN(currentCount) && !isNaN(productCount) && currentCount < productCount) {
                modal.querySelector('.pcw-plus').classList.remove('disabled');
                modal.querySelector('.pcw-minus').classList.remove('disabled');
                modal.querySelector('.js-add-cart').classList.remove('disabled');
            }
            if (isNaN(currentCount) && !isNaN(productCount)) {
                modal.querySelector('.pcw-plus').classList.remove('disabled');
                modal.querySelector('.js-add-cart').classList.remove('disabled');
            }
            if (!isNaN(currentCount) && !isNaN(productCount) && currentCount + 1 >= productCount) {
                modal.querySelector('.pcw-plus').classList.add('disabled');
            }
            // Отключаем кнопку plus, если в наличии 1 единица товара
            if (productCount < 2) {
                modal.querySelector('.pcw-plus').classList.add('disabled');
            }
        }
    } catch (e) {
        console.error(e);
    }
}

function showCard(productId) {
    if (tg) {
        tg.expand();
        if (!tg.BackButton.isVisible) tg.BackButton.show();
        backButtonOffClick();
        tg.BackButton.onClick(hideCard);
        if (tg.MainButton.isVisible) tg.MainButton.hide();
    }
    if ($(window).scrollTop() == 0) $('html, body').animate({ scrollTop: 50 }, 100);
    $('.product-view-wrap').css({ visibility: 'visible' });
    $('.product-view-bg').css({ opacity: '1' });
    $('.product-view').css({ transform: 'translateY(0)' });

    const url = `${location.href.replace(/\?\S+/, '')}?product=${productId}`;
    history.replaceState({}, '', url);

    getProduct(productId);

    $('.product-view-wrap .pcw-count').text(1);
    hideScrollBar();
    setTimeout(() => {
        $('.product-view-wrap').addClass('active');
    }, 500);
}

function hideCard() {
    if (tg) {
        backButtonOffClick();
        if (tg.BackButton.isVisible) tg.BackButton.hide();
        if (!tg.MainButton.isVisible && checkCartLength()) tg.MainButton.show();
    }
    $('.product-view-bg').css({ opacity: '0' });
    $('.product-view').css({ transform: 'translateY(100%)' });
    $('.product-view-wrap').removeClass('active');
    $('.product-view-wrap').removeAttr('data-current-count');

    const url = location.href.replace(/\?\S+/, '');
    history.replaceState({}, '', url);

    showScrollBar();
    setTimeout(() => {
        $('.product-view-wrap').css({ visibility: 'hidden' });
        $('.product-view-wrap .js-product-image').attr('src', '');
        $('.product-view-wrap .js-product-image').removeClass('active');
        $('.product-view-wrap .js-product-image').removeClass('square');
        $('.product-view-wrap .js-product-image').removeClass('vertical-rectangle');
        $('.product-view-wrap .js-product-image').removeClass('horizontal-rectangle');
        $('.product-view-wrap .js-product-title').text('');
        $('.product-view-wrap .js-product-weight').text('');
        $('.product-view-wrap .js-product-description').text('');
        $('.product-view-wrap .js-product-price').text('');
        $('.product-view-wrap .js-product-variant').html('');
        $('.product-view-wrap .js-product-options').html('');
    }, 500);
}

function showScrollBar() {
    $('body').removeClass('scroll-lock');
}

function hideScrollBar() {
    $('body').addClass('scroll-lock');
}

jQuery(document).ready(function($) {

    let $body = $('body');

    /**
     * Добавить в корзину
     */
    $body.on('click', '.ci-price', function(e) {
        e.preventDefault();

        const $productCard = $(this).closest('.catalog-item').find('.catalog-item-product');

        const productId = parseInt($productCard.attr('data-product-id'));
        const productCount = parseInt($productCard.attr('data-available-quantity'));
        const price = parseInt($productCard.attr('data-price'));
        const weight = parseInt($productCard.attr('data-weight'));
        const isVariants = $productCard.attr('data-variants');
        const isOptions = $productCard.attr('data-options');
        const productImg = $productCard.find('img').attr('src');
        const productTitle = $productCard.find('.ci-name').text();

        if (isVariants == 'true' || isOptions == 'true') {
            showCard(productId);
        }

        if (isVariants == 'false' && isOptions == 'false') {
            let count = parseInt($(this).parents('.ci-price-counter')
                .find('.cic-count')
                .text());

            const product = {
                id: productId,
                title: productTitle,
                img: productImg,
                price,
                weight,
                count: 1,
                options: {}
            };

            addCartItem(product);

            $(this).addClass('hidden');
            $(this).parents('.ci-price-counter')
                .find('.ci-counter-wrap')
                .removeClass('hidden');

            $(this).parents('.ci-price-counter')
                .find('.cic-count').text(1);

            if (!isNaN(productCount) && count >= productCount) {
                $(this).parents('.ci-price-counter')
                    .find('.cic-plus')
                    .addClass('disabled');
            }

            $productCard.attr('data-current-count', count);

            if (tg && !tg.MainButton.isVisible) {
                tg.MainButton.show();
            }
        }
    });

    $body.on('click', '.cart-empty', function(e) {
        $(this).addClass('d-none');
        clearCart();
        redirect('index');
    });

    $body.on('input', '.order-form .formInput', function(e) {
        setCartField(this.id, this.value);
        if (this.classList.contains('error')) this.classList.remove('error');
        $('.js-error-text').text('');
    });

    $body.on('change', 'select[name=variant]', function(e) {
        const selectedOption = this.options[this.selectedIndex];
        const modal = document.querySelector('.product-view-wrap');
        const modalWeight = modal.querySelector('.js-product-weight');
        const modalPrice = modal.querySelector('.js-product-price');
        const modalOptions = modal.querySelectorAll('.js-product-options .caption-item');
        const modalCount = modal.querySelector('.pcw-count');
        const weight = selectedOption.dataset.variantWeight;
        const price = selectedOption.dataset.variantPrice;
        modalWeight.innerText = weight ? `${weight} g` : '';
        modalPrice.innerText = price;
        modal.dataset.price = price;
        modal.dataset.weight = weight;
        modal.dataset.totalWeight = weight;
        modal.dataset.count = selectedOption.dataset.variantCount;
        modalCount.innerText = 1;
        modal.querySelector('.pcw-plus').classList.remove('disabled');
        if (modalOptions != null) {
            modalOptions.forEach(option => {
                if (option.parentElement.dataset.required == 'true') {
                    modal.querySelector('.js-add-cart').innerText = 'Выбор опций';
                    modal.querySelector('.js-add-cart').classList.add('options-required');
                }
                option.parentElement.querySelector('.caption-label').classList.remove('text-red');
                option.classList.remove('active');
            });
        }
    });

    $body.on('change', '.js-toggle-delivery', function(e) {
        const cart = getCart();
        const selectedOption = this.options[this.selectedIndex];
        const methodId = selectedOption.value;
        const description = selectedOption.dataset.description;
        let price = parseInt(selectedOption.dataset.price);
        if (isNaN(price)) price = 0;
        let freeFrom = parseInt(selectedOption.dataset.freeFrom);
        if (isNaN(freeFrom)) freeFrom = false;
        const isFullname = parseInt(selectedOption.dataset.isFullname);
        const isAddress = parseInt(selectedOption.dataset.isAddress);
        const isPhone = parseInt(selectedOption.dataset.isPhone);
        const isComment = parseInt(selectedOption.dataset.isComment);

        $('.js-delivery-description').text(description);

        let formHtml = '';

        $('.form-group-section').html('');

        if (isFullname) {
            formHtml += `
            <div class="form-group">
                <input name="fullname" id="fullname" type="text" class="formInput" placeholder="Имя" value="${cart.fullname ? cart.fullname : ''}" required>
            </div>`;
        }

        if (isAddress) {
            formHtml += `
            <div class="form-group">
                <input name="address" id="address" type="text" class="formInput" placeholder="Адрес доставки" value="${cart.address ? cart.address : ''}" required>
            </div>`;
        }

        if (isPhone) {
            formHtml += `
            <div class="form-group">
                <input name="phone" id="phone" inputmode="numeric" type="number" class="formInput" placeholder="Телефон" value="${cart.phone ? cart.phone : ''}" required>
            </div>`;
        }

        if (isComment) {
            formHtml += `
            <div class="form-group">
                <input name="comment" id="comment" type="text" class="formInput" placeholder="Комментарий" value="${cart.comment ? cart.comment : ''}">
            </div>`;
        }

        $('.form-group-section').html(formHtml);

        setCartDelivery(methodId, price, freeFrom);
    });

    $body.on('change', '.js-toggle-payment', function(e) {
        const selectedOption = this.options[this.selectedIndex];
        const methodId = selectedOption.value;
        const methodProviderId = selectedOption.dataset.providerId || false;
        setCartPayment(methodId, methodProviderId);
    });

    /**
     * Уменьшить кол-во
     */
    $body.on('click', '.cic-minus.catalog', function(e) {
        e.preventDefault();

        const $productCard = $(this).closest('.catalog-item').find('.catalog-item-product');
        const productId = parseInt($productCard.attr('data-product-id'));

        let count = parseInt($(this).parents('.ci-counter-wrap')
            .find('.cic-count')
            .text());

        $(this).parents('.ci-price-counter')
            .find('.cic-plus')
            .removeClass('disabled');

        if (count < 2) {
            $(this).parents('.ci-counter-wrap').addClass('hidden');
            $(this).parents('.ci-price-counter')
                .find('.ci-price')
                .removeClass('hidden');

            $productCard.removeAttr('data-current-count');

            removeCartItem(productId);
        } else {
            $(this).parents('.ci-counter-wrap')
                .find('.cic-count')
                .text(count - 1);

            $productCard.attr('data-current-count', count - 1);

            decrementCartItem(productId);
        }

        if (!checkCartLength() && tg && tg.MainButton.isVisible) {
            tg.MainButton.hide();
        }
    });

    /**
     * Увеличить кол-во
     */
    $body.on('click', '.cic-plus.catalog', function(e) {
        e.preventDefault();

        if ($(this).hasClass('disabled')) return false;

        const $productCard = $(this).closest('.catalog-item').find('.catalog-item-product');
        const productId = parseInt($productCard.attr('data-product-id'));
        const productCount = parseInt($productCard.attr('data-available-quantity'));
        const isVariants = $productCard.attr('data-variants');
        const isOptions = $productCard.attr('data-options');

        let count = parseInt($(this).parents('.ci-counter-wrap').find('.cic-count').text());
        if (count + 1 >= productCount) {
            $(this).addClass('disabled');
        }

        if (isVariants == 'true' || isOptions == 'true') {
            showCard(productId);
        }

        if (isVariants == 'false' && isOptions == 'false') {

            if (isNaN(productCount) || (!isNaN(productCount) && count < productCount)) {
                $(this).parents('.ci-counter-wrap')
                    .find('.cic-count')
                    .text(count + 1);

                $productCard.attr('data-current-count', count + 1);

                incrementCartItem(productId);
            }

            if (!isNaN(productCount) && count + 1 >= productCount) {
                $(this).addClass('disabled');
            }
        }
    });

    /**
     * Уменьшить кол-во (в корзине)
     */
    $body.on('click', '.cic-minus.cart', async function (e) {
        e.preventDefault();

        if (this.classList.contains('disabled')) return false;

        const $productCard = $(this).closest('.cart-item-row');
        const index = parseInt($productCard.attr('data-index'));
        const productCount = parseInt($productCard.attr('data-product-count'));
        const itemId = parseInt($productCard.attr('data-product-id'));
        const $priceEl = $productCard.find('.js-price');
        // const oldPrice = parseInt($priceEl.attr('data-price'));
        const itemPrice = parseInt($priceEl.attr('data-item-price'));

        let count = parseInt($(this).parents('.cart-item-counter')
            .find('.cic-count')
            .text());

        let newCount = count - 1

        if (isNaN(productCount) || (!isNaN(productCount) && newCount < productCount)) {
            $(this).parents('.cart-item-counter')
                .find('.cic-plus.cart')
                .removeClass('disabled');

            $(this).closest('.cart-item-counter').removeClass('cart-item-error');
        }

        if (isNaN(productCount) || (!isNaN(productCount) && newCount <= productCount)) {
            $(this).closest('.cart-item-counter').removeClass('cart-item-error');
        }

        if ($productCard.find('.cart-item-error').length == 0) {
            if (tg) {
                tg.MainButton.enable();
            }
        }

        if (count < 2) {
            $productCard.remove();
            removeCartItemForIndex(index);
            if (!checkCartLength) {
                redirect('index')
            }
        } else {
            $(this).parents('.cart-item-counter')
                .find('.cic-count')
                .text(newCount);

            decrementCartItemForIndex(index);
        }

        const discountedItemPrice = await calculateDiscount(itemId, newCount) // Рассчитываем цену одного товара
        const discountedPrice = discountedItemPrice * newCount

        let item_html = `${filterCurrencySymbol(itemPrice * newCount)}`
        // Зачеркиваем цену до скидки
        if (discountedItemPrice < itemPrice) {
            item_html = `<del>${item_html}</del> <b>${filterCurrencySymbol(discountedPrice)}</b>`
        }
        $priceEl.attr('data-price', discountedPrice);
        $priceEl.html(item_html);

    });

    /**
     * Увеличить кол-во (в корзине)
     */
    $body.on('click', '.cic-plus.cart', async function (e) {
        e.preventDefault();

        if (this.classList.contains('disabled')) return false;

        const $productCard = $(this).closest('.cart-item-row');
        const index = parseInt($productCard.attr('data-index'));
        const itemId = parseInt($productCard.attr('data-product-id'));
        const productCount = parseInt($productCard.attr('data-product-count'));
        const $priceEl = $productCard.find('.js-price');
        const itemPrice = parseInt($priceEl.attr('data-item-price'));

        let count = parseInt($(this).parents('.cart-item-counter')
            .find('.cic-count')
            .text());

        const newCount = count + 1;

        if (isNaN(productCount) || (!isNaN(productCount) && count < productCount)) {
            $(this).parents('.cart-item-counter')
                .find('.cic-count')
                .text(newCount);

            incrementCartItemForIndex(index);

            const discountedItemPrice = await calculateDiscount(itemId, newCount) // Рассчитываем цену одного товара
            const discountedPrice = discountedItemPrice * newCount

            let item_html = `${filterCurrencySymbol(itemPrice * newCount)}`

            // Зачеркиваем цену до скидки
            if (discountedItemPrice < itemPrice) {
                item_html = `<del>${item_html}</del> <b>${filterCurrencySymbol(discountedPrice)}</b>`
            }
            $priceEl.attr('data-price', discountedPrice);
            $priceEl.html(item_html);
        }

        if (!isNaN(productCount) && newCount + 1 > productCount) {
            $(this).addClass('disabled');
        }
    });

    /**
     * Уменьшить кол-во (в карточке)
     */
    $body.on('click', '.pcw-minus', function(e) {
        e.preventDefault();

        if (this.classList.contains('disabled')) return false;

        const productCount = parseInt($(this).closest('.product-view-wrap').attr('data-available-quantity'));
        let count = parseInt($(this).parents('.pcw-count-wrap')
            .find('.pcw-count')
            .text());

        if (count > 1) {
            if (isNaN(productCount) || (!isNaN(productCount) && count - 1 < productCount)) {
                $(this).parents('.pcw-count-wrap')
                    .find('.pcw-plus')
                    .removeClass('disabled');
            }
            $(this).parents('.pcw-count-wrap')
                .find('.pcw-count')
                .text(count - 1);

            const $modal = $(this).closest('.product-view-wrap');
            const $priceEl = $(this).closest('.pcw-btn-group').find('.js-product-price');
            const priceRender = parseInt($priceEl.text());
            const weight = parseInt($modal.attr('data-weight'));
            $modal.attr('data-total-weight', weight * (count - 1));
            $priceEl.text(priceRender - (priceRender / count));
        }
    });

    /**
     * Увеличить кол-во (в карточке)
     */
    $body.on('click', '.pcw-plus', function(e) {
        e.preventDefault();

        if (this.classList.contains('disabled')) return false;

        const productCount = parseInt($(this).closest('.product-view-wrap').attr('data-available-quantity'));
        const productCurrentCount = parseInt($(this).closest('.product-view-wrap').attr('data-current-count'));
        let count = parseInt($(this).parents('.pcw-count-wrap')
            .find('.pcw-count')
            .text());

        const newCount = count + 1;

        if (isNaN(productCount) || (!isNaN(productCount) && count < productCount)) {
            $(this).parents('.pcw-count-wrap')
                .find('.pcw-count')
                .text(newCount);

            const $modal = $(this).closest('.product-view-wrap');
            const $priceEl = $(this).closest('.pcw-btn-group').find('.js-product-price');
            const priceRender = parseInt($priceEl.text());
            const weight = parseInt($modal.attr('data-weight'));
            $modal.attr('data-total-weight', weight * (newCount));
            $priceEl.text(priceRender + (priceRender / count));
        }

        if (!isNaN(productCount) && newCount + 1 > productCount) {
            $(this).addClass('disabled');
        }
        if (!isNaN(productCurrentCount) && !isNaN(productCount) && newCount + productCurrentCount >= productCount) {
            $(this).addClass('disabled');
        }
    });

    /**
     * Выбор начинки (в карточке)
     */
    $body.on('click', '.caption-item', function(e) {
        e.preventDefault();

        const $modal = $(this).closest('.product-view-wrap');
        const price = parseInt($(this).attr('data-price'));
        const $productPrice = $('.js-product-price');
        const productCount = parseInt($modal.find('.pcw-count').text());
        let productPrice = parseInt($productPrice.text());

        if (!$(this).parents('.caption-item-checkbox').length) {
            if (!$(this).hasClass('active')) {
                const $activeItem = $(this).parent('div').find('.caption-item.active');
                $activeItem.removeClass('active');
                if ($activeItem.length != 0) {
                    const oldPrice = parseInt($activeItem.attr('data-price'));
                    productPrice -= oldPrice * productCount;
                }
                $productPrice.text(productPrice + (price * productCount));
                $(this).toggleClass('active');
            }
        } else {
            if (!$(this).hasClass('active')) {
                $productPrice.text(productPrice + (price * productCount));
            } else {
                $productPrice.text(productPrice - (price * productCount));
            }
            $(this).toggleClass('active');
        }

        if ($(this).parent().attr('data-required') == 'true') {
            $(this).parent().find('.caption-label').removeClass('text-red');
            let isComplete = true;
            $modal.find('.js-product-options > div[data-required=true]').each((index, item) => {
                if ($(item).find('.caption-item.active').length == 0) isComplete = false;
            });
            if (isComplete) {
                $modal.find('.js-add-cart').text('Add');
                $modal.find('.js-add-cart').removeClass('options-required');
            } else {
                $modal.find('.js-add-cart').text('Выбор опций');
                $modal.find('.js-add-cart').addClass('options-required');
            }
        }
    });

    const productId = getParam('product');
    if (productId) {
        $('.product-view-wrap').attr('data-current-count', $(`.catalog-item-product[data-product-id="${productId}"]`).attr('data-current-count'));

        showCard(productId);
    }

    /**
     * Открыть карточку товара
     */
    $body.on('click', '.js-get-product', function(e) {
        e.preventDefault();

        if (this.classList.contains('disabled')) return false;

        const ProductWrap = $('.product-view-wrap');
        ProductWrap.attr('data-current-count', $(this).attr('data-current-count'));
        ProductWrap.attr('data-available-quantity', $(this).attr('data-available-quantity'));

        this.classList.remove('disabled');

        showCard(this.dataset.productId);
    });

    /**
     * Закрыть карточку товара
     */
    $body.on('click', '.cross-item', function(e) {
        hideCard();
    });

    $body.on('click', '.js-add-cart', function(e) {
        e.preventDefault();

        const $modalCard = $(this).closest('.product-view-wrap');

        if (this.classList.contains('disabled')) return false;

        if (this.classList.contains('options-required')) {
            const $options = $modalCard.find('.js-product-options > div');
            $options.each((index, item) => {
                if (item.dataset.required == 'true' && item.querySelector('.caption-item.active') == null) {
                    item.querySelector('.caption-label').classList.add('text-red');
                    item.scrollIntoView({ block: 'start', behavior: 'smooth' });
                }
            });
            return false;
        }

        const productId = parseInt($modalCard.attr('data-product-id'));
        const price = parseInt($modalCard.attr('data-price'));
        const weight = parseInt($modalCard.attr('data-weight'));
        const productCount = parseInt($modalCard.attr('data-available-quantity'));
        const productImg = $(`.catalog-item-product[data-product-id="${productId}"]`).find('img').attr('src');
        const productTitle = $modalCard.find('.js-product-title').text();
        const count = parseInt($(this).closest('.pcw-btn-group').find('.pcw-count').text());
        const $variant = $modalCard.find('select[name=variant]');
        const $modalOptions = $modalCard.find('.caption-item.active');
        const isVariants = $modalCard.attr('data-variants');
        const isOptions = $modalCard.attr('data-options');
        const options = {};
        let variant = '';
        if ($modalOptions.length > 0) {
            $modalOptions.each((index, item) => {
                const optionTitle = $(item).parent().find('.caption-label').text();
                const optionName = $(item).attr('data-option-name');
                const optionPrice = parseInt($(item).attr('data-price'));
                if (!options[optionTitle]) options[optionTitle] = [];
                options[optionTitle].push({ name: optionName, price: optionPrice });
            });
        }
        if ($variant.length > 0) {
            variant = $variant.val();
        }

        const $counter = $(`.catalog-item-product[data-product-id="${productId}"]`).next();
        let oldCount = parseInt($counter.find('.cic-count').text());

        const product = {
            id: productId,
            title: productTitle,
            img: productImg,
            price,
            weight,
            count,
            options
        };

        if (variant) product.variant = variant;

        if (!checkCartItem(productId)) {
            addCartItem(product);
        } else {
            if (isVariants == 'true' || isOptions == 'true') {
                const cartItems = getCartItems(productId);
                let isFound = false;
                cartItems.forEach(cartItem => {
                    if (cartItem.variant == product.variant && JSON.stringify(cartItem.options) == JSON.stringify(product.options)) {
                        setCountCartItemForIndex(cartItem.index, cartItem.count + count);
                        isFound = true;
                    }
                });
                if (!isFound) addCartItem(product);
            } else setCountCartItem(productId, oldCount + count);
        }

        $(`.catalog-item-product[data-product-id="${productId}"]`).attr('data-current-count', oldCount + count);
        $counter.find('.ci-price').addClass('hidden');
        $counter
            .find('.ci-counter-wrap')
            .removeClass('hidden');

        $counter.find('.cic-count').text(oldCount + count);

        if (!isNaN(productCount) && oldCount + count >= productCount) {
            $counter.find('.cic-plus').addClass('disabled');
        }

        hideCard();

        if (checkCartLength() && tg && !tg.MainButton.isVisible) {
            tg.MainButton.show();
        }
    });

    let startTime = 0;
    let stopTime = 0;
    let st = 0;
    let scroll = 0;
});

$.fn.scrollEnd = function(callback, timeout) {
    $(this).on('scroll', function() {
        var $this = $(this);
        if ($this.data('scrollTimeout')) {
            clearTimeout($this.data('scrollTimeout'));
        }
        $this.data('scrollTimeout', setTimeout(callback, timeout));
    });
};